define(["angularAMD"], function (angularAMD) {
    angularAMD.service('DeterminationService', ['$state','$rootScope', '$filter', '$stateParams', 'config', '$mdDialog', 'MMWService', '$calculater',
        function ($state, $rootScope, $filter, $stateParams, config, $mdDialog, $MMWService, $calculater) {
            this.init = function(options){
                openDialog(options);
            };

            function openDialog(options){
                $mdDialog.dialog(
                    'module/modulesSPC/program/B0503/determination.tmp.html',
                    function(dialog){
                        return {
                            css_url:'module/modulesSPC/program/B0503/determination.css',
                            qc_form_no: options.qc_form_no || '',
                            qc_qty: options.qc_qty || '',
                            qcItem_list:  options.qcItem_list || [],
                            ok_qty: 0,
                            return_qty: 0,
                            scrap_qty: 0,
                            return_reason: '',
                            scrap_reason: '',
                            hold_description: '',
                            beforeShown: function(){
                            },
                            sendResult: function(qc_result){
                                qcFormResultProcess(dialog, qc_result, function(){
                                    var content = {
                                        qc_form_no: dialog.qc_form_no
                                    }
                                    qcform_rule_check(content, function(data){
                                        if(data.check_result == 0){
                                            dialog.hide();
                                            $rootScope.showToast($filter('translate')('determination.msg.success'));
                                        } else if(data.check_result == 1){
                                            dialog.hide();
                                            $rootScope.showAlert(data.hold_description);
                                        } else if(data.check_result == 2){
                                            data.hold_description = data.hold_description.replace( /\\r\\n/g , '\n');
                                            dialog.hold_description = data.hold_description;
                                            abnormalTicket(dialog);
                                        }; 
                                    });                          
                                });  
                            },
                            input_ok_qty: function(event){
                                input_qty(dialog.ok_qty, event, function(num){
                                   dialog.ok_qty = num;
                                });
                            },
                            input_return_qty: function(event){
                                input_qty(dialog.return_qty, event, function(num){
                                    dialog.return_qty = num;
                                 });
                            },
                            input_scrap_qty: function(event){
                                input_qty(dialog.scrap_qty, event, function(num){
                                    dialog.scrap_qty = num;
                                 });
                            },
                            back : function(){
                                if(options.close){
                                    options.close(dialog);
                                } else {
                                    dialog.hide();
                                }
                            }
                        }
                    }
                )
            };

            function input_qty(qty, event, callback){
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function(num, dialog){
                    angular.element(target).removeClass('is-focus');
                    dialog.hide();
                    if(callback)
                        callback(+num);
                },
                function(dialog){
                    angular.element(target).removeClass('is-focus');
                    dialog.hide();
                },
                {
                    defaultNum : qty,
                    decimal : true
                });
            }

            //檢驗單結果判定作業
            function qcFormResultProcess(dialog, qc_result, callback){
                var content = {
                    qc_form_no: dialog.qc_form_no,
                    qc_qty: dialog.qc_qty,
                    ok_qty: dialog.ok_qty,
                    return_qty: dialog.return_qty,
                    scrap_qty: dialog.scrap_qty,
                    return_reason: dialog.return_reason,
                    scrap_reason: dialog.scrap_reason,
                    qc_result: qc_result
                }
                console.log("檢驗單結果判定作業(qc_form_result_process) send:", content);
                // if(callback)
                //     callback();
                $MMWService.sendToSMESServer({
                	uri: 'tcSPC.clsSpc.qc_form_result_process',
                	content : content,
                	success : function(data){
                        console.log("檢驗單結果判定作業(qc_form_result_process) send:", data);
                		if(callback)
                			callback(data);
                	}
                });
            };

            // 異常單開立 (開窗)
            function abnormalTicket(options){
                $mdDialog.dialog(
                    'module/modulesSPC/program/B0503/abnormalTicket.tmp.html',
                    function(dialog){
                        var content = {
                            qc_form_no : options.qc_form_no
                        };
                        erf_win_info_get(content,function(data){
                            dialog.qc_form_no = data.qc_form_no;
                            dialog.op_no = data.op_no;
                            dialog.item_type = data.item_type;
                            dialog.item_no = data.item_no;
                            dialog.item_name = data.item_name;
                            dialog.unit = data.unit;
                            dialog.spec = data.spec;
                            dialog.m_class_no = data.m_class_no;
                            dialog.first_group = data.first_group;
                            dialog.final_group = data.final_group;
                            dialog.hold_description = options.hold_description;
                        });
                        // 照片限制數量
                        var picLimitNum = 5;
                        return {
                            css_url:'module/modulesSPC/program/B0503/abnormalTicket.css',
                            ok_qty: options.ok_qty,
                            return_qty: options.return_qty,
                            scrap_qty: options.scrap_qty,
                            abnormalList:[],
                            back : function(){
                                dialog.hide();
                            },
                            load_abnormal_reason: function(){
                                $rootScope.showQueryList({
                                    key:'m_class_no',
                                    header : [
                                        {label: $filter('translate')('abnormalTicket.queryList.main_class_no'), code:'m_class_no'},
                                        {label: $filter('translate')('abnormalTicket.queryList.second_class_no'), code:'s_class_no'},
                                        {label: $filter('translate')('abnormalTicket.queryList.reason_no'), code:'hold_item_no'},
                                        {label: $filter('translate')('abnormalTicket.queryList.reason_name'), code:'hold_item_name'},
                                        {label: $filter('translate')('abnormalTicket.queryList.description'), code:'memo'}
                                    ],
                                    query: function(conditions, feedback){
                                        // feedback([
                                        //     {m_class_no: 'M_CLASS_01',s_class_no: 'S_CLASS_01',hold_item_no: 'REASON_01',hold_item_name: '品質異常1',memo: '說明1'},
                                        //     {m_class_no: 'M_CLASS_02',s_class_no: 'S_CLASS_02',hold_item_no: 'REASON_02',hold_item_name: '品質異常2',memo: '說明2'},
                                        //     {m_class_no: 'M_CLASS_03',s_class_no: 'S_CLASS_03',hold_item_no: 'REASON_03',hold_item_name: '品質異常3',memo: '說明3'}
                                        // ]);
                                        var content = {
                                            m_class_no : dialog.m_class_no
                                        };
                                        holditem_info_get(content, function(data){
                                            if(data.holditem_info_get && data.holditem_info_get.length > 0){
                                                feedback(data.holditem_info_get);
                                            }else{
                                                $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                                            };
                                        });
                                    },
                                    confirm: function(selectItem, TypeDialog){
                                        TypeDialog.hide();
                                        var _temp = $filter('filter')(dialog.abnormalList, {hold_item_no : selectItem.hold_item_no})
                                        if(_temp && _temp.length == 0){
                                            dialog.abnormalList.push({
                                                hold_item_no : selectItem.hold_item_no,
                                                hold_item_name : selectItem.hold_item_name,
                                                s_class_no : selectItem.s_class_no,
                                                memo : selectItem.memo
                                            });      
                                        }        
                                    }
                                });
                            },
                            removeRow : function(item){
                                for(var i = 0; i < dialog.abnormalList.length; i++){
                                    dialog.abnormalList.splice(dialog.abnormalList.indexOf(item),1);
                                };
                            },
                            load_m_class_No : function(){
                                $rootScope.showQueryList({
                                    key:'m_class_no',
                                    header : [
                                        {label: $filter('translate')('abnormalTicket.queryList.main_class_no'), code:'m_class_no'},
                                        {label: $filter('translate')('abnormalTicket.queryList.description'), code:'memo'},
                                    ],
                                    query: function(conditions, feedback){
                                        // feedback([
                                        //     {m_class_no: '1001',memo: '精油'},
                                        //     {m_class_no: '1004',memo: 'op'},
                                        //     {m_class_no: '1012',memo: 'op-dis'}
                                        // ]);
                                        var content = {};
                                        mclass_info_get(content, function(data){
                                            if(data.mclass_info_get && data.mclass_info_get.length > 0){
                                                feedback(data.mclass_info_get);
                                            }else{
                                                $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                                            };
                                        });  
                                    },
                                    confirm: function(selectItem, TypeDialog){
                                        TypeDialog.hide();
                                        dialog.m_class_no = selectItem.m_class_no;
                                    }
                                });
                            },
                            load_first_group: function(){
                                $rootScope.showQueryList({
                                    key:'m_class_no',
                                    header : [
                                        {label: $filter('translate')('abnormalTicket.queryList.group_no'), code:'group_no'},
                                        {label: $filter('translate')('abnormalTicket.queryList.group_name'), code:'group_name'},
                                        {label: $filter('translate')('abnormalTicket.queryList.op_no'), code:'op_no'},
                                        {label: $filter('translate')('abnormalTicket.queryList.op_name'), code:'op_name'},
                                        {label: $filter('translate')('abnormalTicket.queryList.description'), code:'memo'},
                                        {label: $filter('translate')('abnormalTicket.queryList.main_class_no'), code:'m_class_no'},
                                    ],
                                    query: function(conditions, feedback){
                                        // feedback([
                                        //     {group_no: 'GROUP1',group_name: '品管群組1',op_no: 'OP_1',op_name: '車工1',memo: '說明1',m_class_no: 'M_CLASS_01'},
                                        //     {group_no: 'GROUP2',group_name: '品管群組2',op_no: 'OP_2',op_name: '車工2',memo: '說明2',m_class_no: 'M_CLASS_02'},
                                        //     {group_no: 'GROUP3',group_name: '品管群組3',op_no: 'OP_3',op_name: '車工3',memo: '說明3',m_class_no: 'M_CLASS_03'}
                                        // ]);
                                        var content = {
                                            // 1：查詢第一處理群組
                                            query_type: '1',
                                            m_class_no: dialog.m_class_no,
                                            op_no: dialog.op_no
                                        };
                                        treat_group_info_get(content, function(data){
                                            if(data.treat_group_info_get && data.treat_group_info_get.length > 0){
                                                feedback(data.treat_group_info_get);
                                            }else{
                                                $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                                            };
                                        }); 
                                    },
                                    confirm: function(selectItem, TypeDialog){
                                        TypeDialog.hide();
                                        dialog.first_group = selectItem.group_no;
                                    }
                                });
                            },
                            load_final_group: function(){
                                $rootScope.showQueryList({
                                    key:'m_class_no',
                                    header : [
                                        {label: $filter('translate')('abnormalTicket.queryList.group_no'), code:'group_no'},
                                        {label: $filter('translate')('abnormalTicket.queryList.group_name'), code:'group_name'},
                                        {label: $filter('translate')('abnormalTicket.queryList.op_no'), code:'op_no'},
                                        {label: $filter('translate')('abnormalTicket.queryList.op_name'), code:'op_name'},
                                        {label: $filter('translate')('abnormalTicket.queryList.description'), code:'memo'},
                                        {label: $filter('translate')('abnormalTicket.queryList.main_class_no'), code:'m_class_no'},
                                    ],
                                    query: function(conditions, feedback){
                                        // feedback([
                                        //     {group_no: 'GROUP1',group_name: '品管群組1',op_no: 'OP_1',op_name: '車工1',memo: '說明1',m_class_no: 'M_CLASS_01'},
                                        //     {group_no: 'GROUP2',group_name: '品管群組2',op_no: 'OP_2',op_name: '車工2',memo: '說明2',m_class_no: 'M_CLASS_02'},
                                        //     {group_no: 'GROUP3',group_name: '品管群組3',op_no: 'OP_3',op_name: '車工3',memo: '說明3',m_class_no: 'M_CLASS_03'}
                                        // ]);
                                        var content = {
                                            // 2：查詢最後處理群組
                                            query_type: '2',
                                            m_class_no: dialog.m_class_no,
                                            op_no: dialog.op_no
                                        };
                                        treat_group_info_get(content, function(data){
                                            if(data.treat_group_info_get && data.treat_group_info_get.length > 0){
                                                feedback(data.treat_group_info_get);
                                            }else{
                                                $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                                            };
                                        }); 
                                    },
                                    confirm: function(selectItem, TypeDialog){
                                        TypeDialog.hide();
                                        dialog.final_group = selectItem.group_no;
                                    }
                                });
                            },
                            // 照片
                            picSrcArray: [],
                            erf_image: [],
                            pic_add: function(){
                                if(dialog.picSrcArray.length < picLimitNum){
                                    if(typeof(navigator.camera) !== 'undefined'){
                                        //回傳URI
                                        navigator.camera.getPicture(
                                            function(imageURI) {
                                                
                                                if($rootScope.compressImage)
                                                {
                                                    $rootScope.compressImage(imageURI, 
                                                        function(data){  
                                                            dialog.picSrcArray.push(data);
                                                            $rootScope.$apply();
                                                            }); 
                                                }
                                                else
                                                {
                                                    dialog.picSrcArray.push(imageURI);
                                                    $rootScope.$apply();
                                                }
                                                //$scope.data.scrollLeft = document.getElementById('img-tile-list').clientWidth;
                                            },
                                            function(message) {
                                                //alert('Failed because: ' + message);
                                            },
                                            {
                                                quality: 50,
                                                destinationType: Camera.DestinationType.DATA_URL
                                            }
                                        );
                                    } else if(window.nodeRequire){
                                        //回傳URI
                                        try {
                                            var remote = window.nodeRequire('electron').remote;
                                            remote.dialog.showOpenDialog({
                                                properties: ['openFile', 'multiSelections'],
                                                filters: [
                                                    {name: 'Images', extensions: ['jpg', 'png', 'gif', 'bmp']}
                                                ]
                                            },function(fileList){
                                                $rootScope.showLoading();
                                                $rootScope.$apply();
                                                setTimeout(function(){
                                                    if(fileList){
                                                        if(fileList.length == 0){
                                                            //
                                                        } else if((dialog.picSrcArray.length + fileList.length) > picLimitNum){
                                                            $rootScope.showAlert($filter('translate')('determination.msg.pic_limit', {num:picLimitNum}));
                                                        } else {
                                                            if(window.nodeRequire){
                                                                var fs = window.nodeRequire('fs');
                                                                fileList.forEach(function(fileName){
                                                                    var image = fs.readFileSync(fileName);
                                                                    var file = fileName.split('\\').pop();
                                                                    if(image) {
                                                                        if($rootScope.compressImage)
                                                                        {
                                                                            $rootScope.compressImage(new Buffer(image).toString('base64'), 
                                                                            function(data){                                                       
                                                                            dialog.picSrcArray.push({
                                                                                picSrc: data,
                                                                                picFileName: file
                                                                            })}); 
                                                                        }
                                                                        else
                                                                        {
                                                                            dialog.picSrcArray.push({
                                                                                picSrc: new Buffer(image).toString('base64'),
                                                                                picFileName: file
                                                                            });
                                                                        }

                                                                    }
                                                                });
                                                            }  
                                                        };
                                                    };
                                                    $rootScope.hideLoading();
                                                    $rootScope.$apply();
                                                });
                                            });
                                        } catch (error) {
                                            $('body').append('<input id="fileDialog" type="file" accept=".jpg,.png,.gif,.bmp" multiple size="5" >');
                                            var file_field = $('#fileDialog');
                                            file_field.on('change', function(){
                                                if(file_field[0].files && file_field[0].files.length>0){
                                                    var fileList = [];
                                                    for(var i =0;i<file_field[0].files.length;i++){
                                                        fileList.push(file_field[0].files[i].path);
                                                    }
                                                    if((dialog.picSrcArray.length + fileList.length) > picLimitNum){
                                                        $rootScope.showAlert($filter('translate')('B0207.msg.pic_limit', {num:picLimitNum}));
                                                    } else {
                                                        var fs = window.nodeRequire('fs');
                                                        fileList.forEach(function(fileName){
                                                            var image = fs.readFileSync(fileName);
                                                            if(image)
                                                                dialog.picSrcArray.push(new Buffer(image).toString('base64'));
                                                        });
                                                    }
                                                }
                                                file_field.remove();
                                            });
                                            file_field.click();
                                        }

                                    } else {
                                        $rootScope.showAlert($filter('translate')('common.msg.cant_use_camera'));
                                    };
                                } else {
                                    $rootScope.showAlert($filter('translate')('determination.msg.pic_limit', {num:picLimitNum}));
                                };
                            },
                            pic_delete: function(index){
                                dialog.picSrcArray.splice(index,1);
                            },
                            pic_open: function(index){
                                $gallery.show('#'+(index+1), 'data:image/jpeg;base64,'+dialog.picSrcArray[index], function(){

                                });
                            },
                            confirm: function(){
                                var content = {
                                    qc_form_no: dialog.qc_form_no,
                                    item_type: dialog.item_type,
                                    item_no: dialog.item_no,
                                    spec: dialog.spec,
                                    unit: dialog.unit,
                                    op_no: dialog.op_no,
                                    qc_qty: dialog.ok_qty,
                                    return_qty: dialog.return_qty,
                                    scrap_qty: dialog.scrap_qty,
                                    m_class_no: dialog.m_class_no,
                                    first_group: dialog.first_group,
                                    final_group: dialog.final_group,
                                    hold_description: dialog.hold_description,
                                    erf_image: [],
                                    hold_reason: [],
                                };

                                for(var i=0;i<dialog.picSrcArray.length;i++){
                                    var picSrc = dialog.picSrcArray[i].picSrc;
                                    var picFileName = dialog.picSrcArray[i].picFileName;
                                    content.erf_image.push({
                                        image_src: picSrc,
                                        image_filename: picFileName,
                                        image_format: 'jpg'
                                    });
                                    
                                };

                                for(var i = 0; i < dialog.abnormalList.length; i++){
                                    content.hold_reason.push({
                                        reason_no: dialog.abnormalList[i].hold_item_no
                                    });
                                };

                                erf_create_process(content,function(){
                                    dialog.hide();
                                    options.hide();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                });

                            }
                        };
                    }
                );
            };

            // 檢驗單規則 / 法則檢查
            function qcform_rule_check(content, callback){
                $MMWService.sendToSMESServer({
                	uri: 'tcSPC.clsAbnormal.qcform_rule_check',
                	content : content,
                	success : function(data){
                		if(callback)
                			callback(data);
                	}
                });
            };

            // 異常單開窗資訊取得
            function erf_win_info_get(content, callback){
                // var data = {
                //     qc_form_no: 'TEST-123456789',
                //     item_type: '產品',
                //     item_no: 'ITEM001',
                //     item_name: '品號',
                //     spec: 'SPEC',
                //     unit: 'PCS',
                //     op_no: '1001',
                //     m_class_no: '孔徑',
                //     first_group: '品管群組',
                //     final_group: '結案群組',
                // };
				// if(callback)
				// 	callback(data);
                $MMWService.sendToSMESServer({
                	uri: 'tcSPC.clsAbnormal.erf_win_info_get',
                	content : content,
                	success : function(data){
                		if(callback)
                			callback(data);
                	}
                });
            };

            // 異常原因資訊取得
            function holditem_info_get(content, callback){
                $MMWService.sendToSMESServer({
                	uri: 'tcSPC.clsAbnormal.holditem_info_get',
                	content : content,
                	success : function(data){
                		if(callback)
                			callback(data);
                	}
                });
            };

            // 主分類資訊取得
            function mclass_info_get(content, callback){
                $MMWService.sendToSMESServer({
                	uri: 'tcSPC.clsAbnormal.mclass_info_get',
                	content : content,
                	success : function(data){
                		if(callback)
                			callback(data);
                	}
                });
            };

            // 處理群組資訊取得
            function treat_group_info_get(content, callback){
                $MMWService.sendToSMESServer({
                	uri: 'tcSPC.clsAbnormal.treat_group_info_get',
                	content : content,
                	success : function(data){
                		if(callback)
                			callback(data);
                	}
                });
            };

            // 異常單開立作業
            function erf_create_process(content, callback){
                $MMWService.sendToSMESServer({
                	uri: 'tcSPC.clsAbnormal.erf_create_process',
                	content : content,
                	success : function(data){
                		if(callback)
                			callback(data);
                	}
                });
            };
            
        }
    ])
});
